package com.ruoyi.system.controller;


import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.system.domain.WechatReplyMessageDTO;
import com.ruoyi.system.utils.WechatOfficialUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Map;

/**
 * 【公众号】Controller
 *
 * @author ruoyi
 * @date 2024-11-05
 */
@RestController
@RequestMapping("/public/number")
@Anonymous
public class PublicNumberController {



    @Value("${wechat.public.token}")
    private String publicToken;

    /**
     * 公众号验证通用开发参数
     *
     * @param request
     * @return
     */
    @GetMapping(value = "/wechat")
    @ResponseBody
    public String wechatCheck(HttpServletRequest request) {
        String signature = request.getParameter("signature");
        String timestamp = request.getParameter("timestamp");
        String nonce = request.getParameter("nonce");
        String echostr = request.getParameter("echostr");
        try {
            String[] arr = {publicToken, timestamp, nonce};
            Arrays.sort(arr);
            StringBuilder content = new StringBuilder();
            for (int i = 0; i < arr.length; i++) {
                content.append(arr[i]);
            }
            MessageDigest md = null;
            String temp = null;
            try {
                md = MessageDigest.getInstance("SHA-1");
                byte[] digest = md.digest(content.toString().getBytes());
                temp = WechatOfficialUtils.byteToStr(digest);
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            }
            if ((temp.toLowerCase()).equals(signature)) {
                return echostr;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    @GetMapping(value = "/hollow")
    public String hollow() {
       return "hollow";
    }

    /**
     * 公众号消息内容回调
     *
     * @param request
     * @return
     */
    @PostMapping(value = "/wechat")
    @ResponseBody
    public void wechatCallback(HttpServletRequest request, HttpServletResponse
            response, @RequestParam(value = "codeNum", required = false) String codeNum) throws IOException {
        OutputStream os = response.getOutputStream();
        try {
            Map<String, String> callbackMap = WechatOfficialUtils.xmlToMap(request);
            if (callbackMap != null) {
                String fromUserName = callbackMap.get("FromUserName");
                String toUserName = callbackMap.get("ToUserName");
                String msgType = callbackMap.get("MsgType");
                String event = callbackMap.get("Event");
                String eventKey = callbackMap.get("EventKey");
                String ticket = callbackMap.get("Ticket");
                String content = callbackMap.get("Content");
                String mediaId = callbackMap.get("MediaId");
                String msgID = callbackMap.get("MsgID");
                String status = callbackMap.get("Status");
                String sentCount = callbackMap.get("SentCount");
                String errorCount = callbackMap.get("ErrorCount");
                String articleUrl = callbackMap.get("ArticleUrl");
                if (msgType.equals("text")) {
                    boolean result = sendReplayMessage(os);
                    if (!result) {
                        sendReplayMessage(os);
                    }
                } else if (msgType.equals("image")) {

                } else if (msgType.equals("voice")) {

                } else if (msgType.equals("video")) {

                } else if (msgType.equals("location")) {

                } else if (msgType.equals("event")) {
                    if (event.equals("SCAN") || event.equals("subscribe")) {

                    }
                    if (event.equals("subscribe")) {
                        sendReplayMessage(os);
                    }
                } else if (event.equals("unsubscribe")) {

                } else if (event.equals("CLICK")) {

                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        os.write("".getBytes());
    }

    public Boolean sendReplayMessage(OutputStream os) throws IOException {
        sendReplyContent(os);
        return false;
    }

    private void sendReplyContent(OutputStream os) throws IOException {

        String text = sendReplyText();
        if (text != null) {
            os.write(text.getBytes());
        }

        String image = sendReplyImage();
        if (image != null) {
            os.write(image.getBytes());
        }

        String news = sendReplyNews();
        if (news != null) {
            os.write(news.getBytes());
        }

    }


    /**
     * 回复文字消息
     *
     * @param
     * @param
     * @return
     */
    public String sendReplyText() {
        Long createTime = System.currentTimeMillis() / 1000;
        WechatReplyMessageDTO xml = new WechatReplyMessageDTO();
        xml.setCreateTime(createTime);
        return WechatOfficialUtils.convertXml(xml);
    }

    /**
     * 回复图片消息
     *
     * @param
     * @param
     * @return
     */
    public String sendReplyImage() {
        Long createTime = System.currentTimeMillis() / 1000;
        WechatReplyMessageDTO xml = new WechatReplyMessageDTO();
        xml.setCreateTime(createTime);
        return WechatOfficialUtils.convertXml(xml);
    }

    /**
     * 回复图文消息
     *
     * @param
     * @param
     * @return
     */
    public String sendReplyNews() {
        Long createTime = System.currentTimeMillis() / 1000;
        WechatReplyMessageDTO xml = new WechatReplyMessageDTO();
        xml.setCreateTime(createTime);
        return WechatOfficialUtils.convertXml(xml);
    }

}
